package com.team.book.configuration;

import com.team.book.handler.LoginFailureHandler;
import com.team.book.provider.DaoAuthProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

/**
 * Created by haolw on 4/22/17.
 *
 * @version 0.0.1
 */
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;
    @Autowired
    private DaoAuthProvider daoAuthProvider;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthProvider);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/**","**/favicon.ico");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/download","/health/**","/shutdown/**")
                .permitAll()
                .antMatchers("/login/**")
                .permitAll()
                .antMatchers("/guide/**")
                .permitAll()
                .antMatchers("/**").hasAnyAuthority("user","系统管理员","审计管理员")
                .and().formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/", true)
                .failureHandler(loginFailureHandler)
                .permitAll()
                .and().logout()
                .logoutSuccessUrl("/login")
                .permitAll()
                .and().exceptionHandling()
                .accessDeniedPage("/login")
                .and().csrf()
                .disable().headers().frameOptions().disable();
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }
}
